import fs from 'fs';
import { resolve } from 'path';
import { argv } from 'process';

const [_, __, type, fileName] = argv;

const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = (date.getDate()).toString().padStart(2, '0');
const hour = (date.getHours()).toString().padStart(2, '0');
const minute = (date.getMinutes()).toString().padStart(2, '0');
const second = (date.getSeconds()).toString().padStart(2, '0');

const fullFileName = fileName ? `${year}${month}${day}-${fileName}.md` : `${year}${month}${day}.md`;

const init = () => {
  if (type === 'daily') {
    const path = resolve(import.meta.dirname, `../content/daily/${year}/${month}`, fullFileName);
    const fileIsExist = checkFileExist(path);
    if (fileIsExist) {
      console.log(`${path} is exist file.`);
      return;
    }
    writeFile(path);
  } else if (type === 'article') {
    const [prefix] = fileName.split('/');
    const path = resolve(import.meta.dirname, `../content/blog/${prefix}`, fullFileName);
    const fileIsExist = checkFileExist(path);
    if (fileIsExist) {
      console.log(`${path} is exist file.`);
      return;
    }
    writeFile(path);
  } else {
    console.log('type is not support!');
  }
};

const writeFile = (path: string) => {
  const ws = fs.createWriteStream(path);
  const date = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
  const content = getMarkdownContent(fileName, date);
  ws.write(content);
  ws.end();
};

const checkFileExist = (path: string) => {
  try {
    fs.statSync(path);
    return true;
  } catch {
    return false;
  }
};

const getMarkdownContent = (title: string, date: string) => {
  const content = `
    ---
    title: ${title || ''}
    date: ${date || ''}
    weather: 
    ---
  `;

  let text = '';
  const arr = content.split('\n');
  for (let i = 0 ; i < arr.length ; i ++) {
    if (i === 0 && arr[i].trim() === '') {
      continue;
    }
    text += arr[i].trim();
    if (i !== arr.length - 1) {
      text += '\n';
    }
  }
  return text;
};

init();
